<template>
  <div class="my-contests-container">
    <div class="page-header">
      <h2>我的竞赛</h2>
      <div class="header-actions">
        <el-button 
          type="primary" 
          :icon="Plus" 
          @click="goToCreateContest" 
          round
        >
          创建竞赛
        </el-button>
        <div class="filter-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索竞赛标题"
            class="filter-item"
            :prefix-icon="Search"
            @input="handleSearch"
            clearable
          />
          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            class="filter-item"
            @change="handleFilter"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col v-for="contest in displayContests" :key="contest.id" :sm="24" :md="12" :lg="8" :xl="6">
        <el-card class="contest-card" shadow="hover">
          <div class="contest-cover">
            <el-image 
              :src="contest.coverImage" 
              fit="cover" 
              class="cover-image"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon size="40"><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="contest-status">
              <el-tag
                :type="getStatusType(contest.status)"
                :effect="getStatusEffect(contest.status)"
                size="small"
                round
              >
                {{ getStatusText(contest.status) }}
              </el-tag>
            </div>
          </div>
          
          <div class="contest-info">
            <h3 class="contest-title">{{ contest.title }}</h3>
            <p class="contest-description">{{ truncateText(contest.description, 80) }}</p>
            <div class="contest-meta">
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(contest.startTime) }}</span>
              </div>
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>{{ contest.currentParticipants || 0 }} 人参与</span>
              </div>
            </div>
            <div class="contest-actions">
              <el-button type="primary" round @click="viewContestDetail(contest.id)">
                查看详情
              </el-button>
              <el-button 
                type="success" 
                round 
                v-if="canJoinContest(contest)"
                @click="joinContest(contest.id)"
              >
                立即参与
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-if="!loading && displayContests.length === 0" class="empty-container">
      <el-empty description="您还没有创建任何竞赛" />
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        hide-on-single-page
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getContestList } from '@/api/contest'
import { getUserInfo } from '@/api/user'
import { Calendar, User, Picture, Search, Plus } from '@element-plus/icons-vue'

const router = useRouter()
const contests = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const statusFilter = ref('')
const currentUser = ref(null)

// 状态选项（包含待审核选项）
const statusOptions = [
  { value: '', label: '全部状态' },
  { value: '0', label: '待审核' },
  { value: '1', label: '进行中' },
  { value: '2', label: '已拒绝' },
  { value: '3', label: '已取消' },
  { value: '4', label: '已结束' }
]

// 获取当前用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200) {
      currentUser.value = res.data
      // 获取用户信息后加载竞赛列表
      fetchContests()
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    ElMessage.warning('无法获取用户信息，请刷新页面重试')
  }
}

// 获取竞赛列表
const fetchContests = async () => {
  if (!currentUser.value || !currentUser.value.id) {
    ElMessage.warning('用户信息不完整，无法获取竞赛列表')
    return
  }

  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      keyword: searchQuery.value,
      status: statusFilter.value,
      creatorId: currentUser.value.id // 只查询当前用户创建的竞赛
    }
    const res = await getContestList(params)
    contests.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取竞赛列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '未设置'
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 截断文本
const truncateText = (text, length) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info'    // 待审核
    case 1: return 'success' // 已通过
    case 2: return 'danger'  // 已拒绝
    case 3: return 'warning' // 已取消
    case 4: return ''        // 已结束
    default: return 'info'
  }
}

// 获取状态效果
const getStatusEffect = (status) => {
  return status === 0 ? 'plain' : 'light'
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '进行中'
    case 2: return '已拒绝'
    case 3: return '已取消'
    case 4: return '已结束'
    default: return '未知状态'
  }
}

// 过滤后的竞赛列表
const displayContests = computed(() => {
  return contests.value
})

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchContests()
}

// 处理过滤
const handleFilter = () => {
  currentPage.value = 1
  fetchContests()
}

// 处理页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchContests()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchContests()
}

// 是否可以参与竞赛
const canJoinContest = (contest) => {
  return contest.status === 1 && 
    (!contest.participantLimit || contest.currentParticipants < contest.participantLimit)
}

// 查看竞赛详情
const viewContestDetail = (id) => {
  router.push(`/contest/detail/${id}`)
}

// 参与竞赛
const joinContest = (id) => {
  router.push(`/contest/detail/${id}`)
}

// 跳转到创建竞赛页面
const goToCreateContest = () => {
  router.push('/contest/create')
}

// 在组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
.my-contests-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 15px;
      align-items: center;
      
      .filter-container {
        display: flex;
        gap: 10px;
        
        .filter-item {
          width: 200px;
        }
      }
    }
  }
  
  .contest-card {
    margin-bottom: 20px;
    overflow: hidden;
    transition: transform 0.3s;
    border-radius: 12px;
    
    &:hover {
      transform: translateY(-5px);
    }
    
    .contest-cover {
      position: relative;
      height: 160px;
      overflow: hidden;
      
      .cover-image {
        width: 100%;
        height: 100%;
      }
      
      .image-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f5f7fa;
        color: #909399;
      }
      
      .contest-status {
        position: absolute;
        top: 10px;
        right: 10px;
      }
    }
    
    .contest-info {
      padding: 15px;
      
      .contest-title {
        margin: 0 0 10px 0;
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
      
      .contest-description {
        margin: 0 0 15px 0;
        font-size: 14px;
        color: #606266;
        line-height: 1.5;
        height: 42px;
        overflow: hidden;
      }
      
      .contest-meta {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
        
        .meta-item {
          display: flex;
          align-items: center;
          gap: 5px;
          font-size: 13px;
          color: #909399;
          
          .el-icon {
            font-size: 14px;
          }
        }
      }
      
      .contest-actions {
        display: flex;
        gap: 10px;
        justify-content: space-between;
      }
    }
  }
  
  .loading-container, .empty-container {
    padding: 30px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

@media screen and (max-width: 768px) {
  .my-contests-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
      
      .header-actions {
        width: 100%;
        flex-direction: column;
        align-items: stretch;
        
        .filter-container {
          margin-top: 10px;
          flex-direction: column;
          
          .filter-item {
            width: 100%;
          }
        }
      }
    }
  }
}
</style> 